import {
  globalAPI
} from "../../api/index"
import {
  throttle,
  debounce,
  returnStatus
}
from '../../utils/util'

const getInf = (str, key) => str.replace(new RegExp(`${key}`, 'g'), `%%${key}%%`).split('%%');
// pages/search/index.js
const urlEm = ['/pages/search/goods/index', '/pages/search/note/index', '/pages/mine/attention/index']
var appInst = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tab: 0,
    result: [],
    cache: {},
    nvabarData:{
      showCapsule:1
    }
  },
  // 改变值
  onChange({
    detail
  }) {},
  // 切换tab
  onChangeTab({
    detail: {
      name: tab
    }
  }) {
    this.setData({
      tab
    })
  },
  // 去除首尾的空格
  trim: function (s) {
    return s.replace(/(^\s*)|(\s*$)/g, "");
  },
  toPathByHistory({
    currentTarget: {
      dataset: {
        path: url
      }
    }
  }) {
    url.includes('?') && (wx.navigateTo({
      url,
    }))
    wx.switchTab({
      url: '/pages/note/index'
    });

  },
  onClearHistory() {
    const _this = this
    wx.removeStorage({
      key: 'search',
      success: (result) => {
        wx.showToast({
          title: '删除成功',
          icon: 'success',
          duration: 800,
          mask: false,
          success: (result) => {
            setTimeout(() => {
              _this.getCache()
            }, 800);
          },
        });
      },
      fail: () => {},
      complete: () => {}
    });
  },
  // 搜索结果
  toPath({
    currentTarget: {
      dataset: {
        index
      }
    }
  }) {
    const {
      tab,
      result_pre
    } = this.data
    let keyword = result_pre[index]
    const url = urlEm[tab] + '?key=' + keyword
    let search_key = wx.getStorageSync('search') || {};
    search_key[keyword] = url
    wx.setStorageSync('search', search_key)
    wx.navigateTo({
      url
    });
  },

  getCache() {
    this.setData({
      cache: []
    })
    wx.getStorage({
      key: 'search',
      success: (result) => {
        this.setData({
          cache: result.data
        })
      },
    });
  },

  onChangeKeyword({
    detail: keyword
  }) {
    const _this = this
    async function getRes() {
      const res = await globalAPI.querySearchByKey({
        keyword,
        type: _this.data.tab
      })
      const _ = await returnStatus(res)
      let result = []
      _.forEach(item => {
        item = _this.trim(item)
        const temp = getInf(item, keyword)
        temp && result.push(temp)
      })
      _this.setData({
        result,
        result_pre: _,
        keyword
      })
      console.info('result', _this.data.result)
    }
    debounce(getRes)()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      keyword: '',
      result: [],
      result_pre: [],
    })
    this.getCache()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})